﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using NCS.IConnect.ApplicationContexts;
using JM.JCY.Common;
using System.IO;
using System.Globalization;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint;
using System.Web.Security;
using Microsoft.SharePoint.Administration.Claims;
using System.Collections;

namespace JM.JCY.SharePointComponent.UserManagement.CreateUser
{
    public partial class CreateUserUserControl : UserControl, ICallbackEventHandler
    {

        public int deptId { get; set; }
        public int jobTitleId { get; set; }
        public string deptName { get; set; }
        public string jobTitle { get; set; }
        public string IsMain { get; set; }
        static string JCYUrl = System.Configuration.ConfigurationManager.AppSettings["JCYUrl"].ToString();
        public string _userName
        {
            set { ViewState["_userName"] = value; }
            get { return (string)ViewState["_userName"]; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string callbackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCallback", "context", false);
            string callbackScript = string.Format("function CallServer(arg,context){{ {0}  }}", callbackReference);
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
            this.ddlDept.SelectedIndex = 0;
            _userName = ApplicationContext.Current.UserName;
            if (!IsPostBack)
            {
                using (UserManagementProxy proxy = new UserManagementProxy())
                {
                    DataSetUserManagement.T_DepartmentDataTable dtDept = proxy.GetAllDepartment();
                    this.ddlDept.DataSource = dtDept;
                    ddlDept.DataTextField = "DeptName";
                    ddlDept.DataValueField = "ID";
                    ddlDept.DataBind();

                    cblDept.DataSource = dtDept;
                    cblDept.DataTextField = "DeptName";
                    cblDept.DataValueField = "ID";
                    cblDept.DataBind();

                }

                DepartmentTitleDataSet.T_DepartmentJobTitleDataTable dt = new DepartmentTitleDataSet.T_DepartmentJobTitleDataTable();
                Session["GridViewDataSource"] = dt;
            }
        }

        public string GetCallbackResult()
        {

            return RenderControl(GridViewDeptList);
        }

        //Realize ICallbackEventHandler member RaiseCallbackEvent
        public void RaiseCallbackEvent(string eventArgument)
        {

            string[] searchCriteria = new string[4];
            if (eventArgument.IndexOf('|') > 0)    //Click Search button to retrieve data
            {
                string[] r = eventArgument.Split('|');
                searchCriteria = Regex.Split(r[1], "@&@", RegexOptions.IgnoreCase);
                if (searchCriteria.Length == 5)
                {
                    deptId = Int32.Parse(searchCriteria[1]);
                    jobTitleId = Int32.Parse(searchCriteria[2]);
                    deptName = searchCriteria[3];
                    jobTitle = searchCriteria[4];

                    var gvDT = (DepartmentTitleDataSet.T_DepartmentJobTitleDataTable)Session["GridViewDataSource"];
                    var gvDT2 = (DepartmentTitleDataSet.T_DepartmentJobTitleDataTable)gvDT.Copy();
                    if (gvDT.Rows.Count > 0)
                    {
                        bool isExist = false;
                        foreach (DepartmentTitleDataSet.T_DepartmentJobTitleRow row in gvDT.Rows)
                        {
                            if (jobTitleId == row.JobTitleId && deptName == row.DeptName)
                            {
                                isExist = true;
                                break;
                            }
                        }
                        if (!isExist)
                        {
                            DepartmentTitleDataSet.T_DepartmentJobTitleRow djRow = gvDT2.NewT_DepartmentJobTitleRow();
                            djRow.DeptId = deptId;
                            djRow.DeptName = deptName;
                            djRow.JobTitleId = jobTitleId;
                            djRow.JobTitle = jobTitle;
                            gvDT2.Rows.Add(djRow);
                            Session["GridViewDataSource"] = gvDT2.Copy();
                            this.GridViewDeptList.DataSource = gvDT2;
                            this.GridViewDeptList.DataBind();
                        }
                        else
                        {
                            this.GridViewDeptList.DataSource = gvDT;
                            this.GridViewDeptList.DataBind();
                        }

                    }
                    else
                    {
                        DepartmentTitleDataSet.T_DepartmentJobTitleRow djRow = gvDT.NewT_DepartmentJobTitleRow();
                        djRow.DeptId = deptId;
                        djRow.DeptName = deptName;
                        djRow.JobTitleId = jobTitleId;
                        djRow.JobTitle = jobTitle;
                        gvDT.Rows.Add(djRow);
                        Session["GridViewDataSource"] = gvDT.Copy();
                        this.GridViewDeptList.DataSource = gvDT.Copy();
                        this.GridViewDeptList.DataBind();
                    }
                }
                //RemovedControl action
                else if (searchCriteria.Length == 2)
                {
                    var gvDT = (DepartmentTitleDataSet.T_DepartmentJobTitleDataTable)Session["GridViewDataSource"];

                    int id = Convert.ToInt32(searchCriteria[1]);
                    gvDT.Rows.Remove(gvDT.FindByJobTitleId(id));

                    Session["EditGridViewSource"] = gvDT.Copy();
                    GridViewDeptList.DataSource = gvDT;
                    GridViewDeptList.DataBind();

                }

            }


        }

        private string RenderControl(Control control)
        {
            StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
            HtmlTextWriter writer2 = new HtmlTextWriter(writer1);

            control.RenderControl(writer2);
            writer2.Flush();
            writer2.Close();

            return writer1.ToString();
        }

        protected void imgSave_Click(object sender, ImageClickEventArgs e)
        {
            var deptArray = new ArrayList();
            using (UserManagementProxy proxy = new UserManagementProxy())
            {

                DepartmentTitleDataSet.T_DepartmentJobTitleDataTable gvDT = (DepartmentTitleDataSet.T_DepartmentJobTitleDataTable)Session["GridViewDataSource"];
                DataSetUserManagement ds = new DataSetUserManagement();

                DataSetUserManagement.T_UserInfoDataTable userDT = ds.T_UserInfo;
                DataSetUserManagement.T_UserInfoRow userRow = userDT.NewT_UserInfoRow();
                userRow.UserName = this.txtName.Text.Trim();
                userRow.Gender = this.rbGender.SelectedValue;
                userRow.Status = this.rblStatus.SelectedValue;
                userRow.IsDeleted = false;
                if (this.rbGender.SelectedValue == "男")
                    userRow.PhotoImagePath = JCYConstant.StaffProfile.DefaultPicturePathMan;
                else
                    userRow.PhotoImagePath = JCYConstant.StaffProfile.DefaultPicturePathWoman;
                JCYUtility.UpdateCommonFields(userRow, "admin");
                userDT.Rows.Add(userRow);

                // add user to membership and sharepoint group
                CreateNewUser(this.txtName.Text);

                DataSetUserManagement.T_UserDepartmentDataTable userDeptDT = ds.T_UserDepartment;
                DataSetUserManagement.T_UserJobTitleDataTable userJobTitleDT = ds.T_UserJobTitle;
                foreach (DepartmentTitleDataSet.T_DepartmentJobTitleRow row in gvDT.Rows)
                {
                    if (!deptArray.Contains(row.DeptId.ToString()))
                    {
                        DataSetUserManagement.T_UserDepartmentRow userDeptRow = userDeptDT.NewT_UserDepartmentRow();
                        userDeptRow.UserId = userRow.ID;
                        userDeptRow.DepartmentId = row.DeptId;
                        userDeptRow.IsDeleted = false;
                        JCYUtility.UpdateCommonFields(userDeptRow, "admin");
                        userDeptDT.Rows.Add(userDeptRow);
                        deptArray.Add(row.DeptId.ToString());
                    }


                    DataSetUserManagement.T_UserJobTitleRow userJobTitleRow = userJobTitleDT.NewT_UserJobTitleRow();
                    userJobTitleRow.UserId = userRow.ID;
                    userJobTitleRow.JobTitleId = row.JobTitleId;
                    userJobTitleRow.IsMain = true;
                    userJobTitleRow.IsDeleted = false;
                    JCYUtility.UpdateCommonFields(userJobTitleRow, "admin");
                    userJobTitleDT.Rows.Add(userJobTitleRow);

                    // add user into group
                    DataSetUserManagement.T_DepartmentDataTable dept = proxy.GetDeptById(row.DeptId, string.Empty);
                    if (dept.Rows.Count > 0)
                    {
                        SPUser spUser = SPContext.Current.Web.EnsureUser(this.txtName.Text);
                        if (!IsExistUser(spUser, dept[0].DeptName))
                            AddUserToGroup(spUser, dept[0].DeptName);
                    }

                }

                proxy.CreateNewDepartment(ds);
                ClearSession();

               
                UserInfoDataSet.T_DeptMgrDataTable dtDeptMgr = new UserInfoDataSet.T_DeptMgrDataTable();
                foreach (ListItem li in this.cblDept.Items)
                {
                    if (li.Selected)
                    {
                       UserInfoDataSet.T_DeptMgrRow dr = dtDeptMgr.NewT_DeptMgrRow();
                       dr.UserName = this.txtName.Text.Trim();
                       dr.UserId = userRow.ID;
                       dr.DeptId = Int32.Parse(li.Value);
                       dtDeptMgr.Rows.Add(dr);

                       SPUser spUser = SPContext.Current.Web.EnsureUser(this.txtName.Text);
                       string deptName = proxy.GetDepartmentTitleById(dr.DeptId).T_Department.Rows[0]["DeptName"].ToString();
                       AddUserToMgrGroup(spUser, deptName);
                        
                    }
                }

                proxy.CreateDeptMgr(dtDeptMgr);

            }

            CreateDocumentLibrary(this.txtName.Text.Trim(), this.txtName.Text.Trim());
            Response.Redirect("StaffMgr.aspx");
        }

        private void CreateNewUser(string _userName)
        {

            Membership.CreateUser(_userName, JCYConstant.defualtPW);
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.PersonalSite])
                    {
                        web.AllowUnsafeUpdates = true;
                        SPUser spUser = web.EnsureUser(_userName);

                        SPGroup spGroup = web.SiteGroups[JCYConstant.MemberGroup];
                        spGroup.AddUser(spUser);
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        private void CreateDocumentLibrary(string docName, string docDesc)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.PersonalSite])
                    {
                        web.AllowUnsafeUpdates = true;
                        web.Lists.Add(docName, docDesc, SPListTemplateType.DocumentLibrary);
                        web.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        public void AddUserToGroup(SPUser user, string groupname)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyDept])
                    {
                        if (!IsExistUser(user, groupname))
                        {
                            web.AllowUnsafeUpdates = true;
                            web.SiteGroups[groupname].AddUser(user);
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }

        public bool IsExistUser(SPUser user, string groupname)
        {
            bool exist = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
               
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyDept])
                    {
                       
                        SPUserCollection users = web.SiteGroups[groupname].Users;
                        foreach (SPUser userlist in users)
                        {
                           
                            if (userlist.ToString().ToLower() == user.LoginName.ToLower())
                                exist = true;
                        }
                    }
                }
            });

            return exist;
           

        }

        private void ClearSession()
        {
            Session["GridViewDataSource"] = null;
            Session.Remove("GridViewDataSource");
        }

        protected void GridViewDeptList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton ib = (ImageButton)e.Row.Cells[2].FindControl("imgBtnDelete");
                ib.Attributes.Add("onclick", "javascript:return DeleteUserDept(" + ib.CommandArgument + ")");

            }
        }



        public void AddUserToMgrGroup(SPUser user, string groupname)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(JCYUrl))
                {
                    using (SPWeb web = site.AllWebs[JCYConstant.SiteName.MyDept])
                    {
                        if (!IsExistUser(user, groupname))
                        {
                            web.AllowUnsafeUpdates = true;
                            web.SiteGroups[groupname].AddUser(user);
                            web.AllowUnsafeUpdates = false;
                        }
                    }
                }
            });
        }

    }
}
